package com.longshen.dubbo.api.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.longshen.dubbo.api.anno.TradeRequired;
import com.longshen.dubbo.api.base.Contents;
import com.longshen.dubbo.api.base.ErrorCode;
import com.longshen.dubbo.api.base.SessionBean;
import com.longshen.dubbo.api.exception.DubboApiException;
import com.longshen.dubbo.api.tools.ServletTools;

import lombok.extern.slf4j.Slf4j;

/**
 * 检查登录状态
 * 
 * @author longshen
 *
 */
@Slf4j
@Component
public class TradeRequiredInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		TradeRequired  tradeRequired=method.getAnnotation(TradeRequired.class);
	     
		if (tradeRequired != null && StringUtils.isNotBlank(tradeRequired.tradeCode())) {
			HttpSession session = ServletTools.getSession(false);
			if (session == null) {
             // 用户未登录
				throw new DubboApiException(ErrorCode.E_000002);
			}

			SessionBean sessionBean = (SessionBean) session.getAttribute(Contents.SESSION_BEAN);
			if (sessionBean == null) {
				throw new DubboApiException(ErrorCode.E_000002);
			}
			String tradeCodes=sessionBean.getTradecodes();
			log.info("交易权限验证");
			if(!StringUtils.contains(tradeCodes,tradeRequired.tradeCode()+",")) {
				throw new DubboApiException(ErrorCode.E_000007);

			}

		}
		return true;
	}

}
